package com.idea.zd.sys.train.http;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;

public class HttpTest {


    public static void post(String strUrl,Map<String,Object> params){
        HttpURLConnection httpURLConnection;
        OutputStreamWriter outputStreamWriter;
        int i = 0;

        try {
            URL url = new URL(strUrl);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Content-Type","text/html");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setReadTimeout(30000);//连接超时时间
            httpURLConnection.setReadTimeout(30000);//设置读取时间
            httpURLConnection.connect();

            outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream());
            outputStreamWriter.write(JSONObject.toJSONString(params).toCharArray());
            outputStreamWriter.flush();
            outputStreamWriter.close();

            //读取响应
            int code = httpURLConnection.getResponseCode();

            if(httpURLConnection.getConnectTimeout() == 30000){
                System.out.println("请求超时"+i);
            }


            if(code == 200){

                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                String str;

                if((str = bufferedReader.readLine()) != null){
                    System.out.println(str);
                }

            }


        } catch (MalformedURLException e) {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }


    }

    public static void main(String [] args){
        post("http://api.fansiji.com/sys_db/getAiqiyiUrl",null);
    }
}
